// pages/video/video.js
const app = getApp()
Page({
  data: {
    videoList: [],
    activeIndex: 0,
    videoContexts: [],
    isPlaying: true,
    current: 0 // 新增 swiper 当前项控制
  },

  onLoad(options) {
    const collection = wx.getStorageSync('collection')
    this.setData({
      activeIndex: collection.index || 0,
      current: collection.index || 0 // 初始化 swiper 位置
    })
  },

  onReady() {
    const collection = wx.getStorageSync('collection')
    app.$http.get('/app/media/list', {
      pageNum: 1,
      pageSize: 5,
      collectionId: collection.id
    }).then(res => {
      this.setData({
        videoList: res.data.records,
        // 确保索引不越界
        activeIndex: Math.min(this.data.activeIndex, res.data.records.length - 1),
        current: Math.min(this.data.activeIndex, res.data.records.length - 1)
      }, () => {
        // 延迟创建 video 上下文确保组件已渲染
        setTimeout(() => {
          const contexts = res.data.records.map((_, index) => {
            return wx.createVideoContext(`video${index}`)
          })
          this.setData({
            videoContexts: contexts
          }, () => {
            // 播放指定位置的视频
            if (contexts[this.data.activeIndex]) {
              contexts[this.data.activeIndex].play()
            }
          })
        }, 300)
      })
    })
  },

  onShow() {
    const { activeIndex, videoContexts } = this.data
    if (videoContexts[activeIndex]) {
      videoContexts[activeIndex].play()
      this.setData({ isPlaying: true })
    }
  },

  onSwiperChange(e) {
    const newIndex = e.detail.current
    const { videoContexts, activeIndex } = this.data
    
    if (videoContexts[activeIndex]) {
      videoContexts[activeIndex].pause()
    }
    
    if (videoContexts[newIndex]) {
      videoContexts[newIndex].play()
      this.setData({
        activeIndex: newIndex,
        isPlaying: true
      })
    }
  },

  togglePlay() {
    const { activeIndex, videoContexts, isPlaying } = this.data
    const currentVideo = videoContexts[activeIndex]
    if (currentVideo) {
      if (isPlaying) {
        currentVideo.pause()
      } else {
        currentVideo.play()
      }
      this.setData({ isPlaying: !isPlaying })
    }
  },

  onHide() {
    const { activeIndex, videoContexts } = this.data
    if (videoContexts[activeIndex]) {
      videoContexts[activeIndex].pause()
    }
  },

  onUnload() {
    const { activeIndex, videoContexts } = this.data
    if (videoContexts[activeIndex]) {
      videoContexts[activeIndex].pause()
    }
    let collection = wx.getStorageSync('collection')
    app.$http.get('/app/collection/'+collection.id).then(res=>{
      collection = res.data
      collection.views = collection.views + 1
      app.$http.put('/app/collection/update', collection)
    })
  }
})